package controllers;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Category;
import models.Course;
import models.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import service.CategoryDao;
import service.CourseDao;
import service.HibernateUtil;
import service.UserDao;

public class CourseController extends HttpServlet {

    private static String titleNew = "New course";
    private static String titleEdit = "Edit course";
    // private List<Course> courses;
    private HibernateUtil HU = new HibernateUtil();
    private Session session = HU.openSession();
    private CourseDao dao = new CourseDao(session);
    private UserDao udao = new UserDao(session);
    private CategoryDao cdao = new CategoryDao(session);

    /*
     * HTTP GET request
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        HttpSession sessie = request.getSession(true);

        HU = new HibernateUtil();
        session = HU.openSession();
        dao = new CourseDao(session);
        udao = new UserDao(session);
        cdao = new CategoryDao(session);
        
        
        //ophalen van courses van een specifieke categorie
        if (request.getParameter("id") != null) {
            long id = Long.parseLong(request.getParameter("id"));

            Category category = cdao.get(String.valueOf(id));
            Set<Course> coursesOfCategory = category.getCourses();

            request.setAttribute("coursesOfCategory", coursesOfCategory);
            forward(request, response, null);
        } //ophalen van gegevens course
        else if (request.getParameter("courseID") != null) {
            Long id = Long.parseLong(request.getParameter("courseID"));
            request.setAttribute("courseID", id);

            Course course = dao.get(id);
            Date startDate = course.getStartDate();
            Date endDate = course.getEndDate();
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String startDateString = formatter.format(startDate);
            String endDateString = formatter.format(endDate);
            System.out.println("Startdate: " + startDateString + ", enddate: " + endDateString);
            request.setAttribute("startDate", startDateString);
            request.setAttribute("endDate", endDateString);
            request.setAttribute("selectedCourse", course);

            try {
                List<User> teacherslist = new ArrayList<User>();
                for (User u : course.getUsers()) {
                    if (u.getStatus().equals("Tutor")||u.getStatus().equals("Admin")) {
                        teacherslist.add(u);
                        request.setAttribute("courseTeachers", teacherslist);
                    }
                }
            } catch (Exception e) {
                System.out.println("teachers of course: "+ e);
            }
            
            try {
                List<User> teacherslist = new ArrayList<User>();
                for (User u : udao.findAll()) {
                    if (u.getStatus().equals("Tutor")||u.getStatus().equals("Admin")) {
                        teacherslist.add(u);
                        request.setAttribute("teachers", teacherslist);
                    }
                }
            } catch (Exception e) {
                System.out.println("teachers in general: "+e);
            }

            for (Category c : cdao.findAll()) {
                for (Course current : c.getCourses()) {
                    if (current.getCourseID() == id) {
                        request.setAttribute("category", c);
                    }
                }
            }
            

            forward(request, response, null);
        } else {
            List<Category> categories = cdao.findAll();
            sessie.setAttribute("categories", categories);
            forward(request, response, null);
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        long id = 0;
        String name = new String();
        String language = new String();
        String description = new String();
        Date startDate = new Date();
        Date endDate = new Date();
        String category = new String();
        double price = 0.0;
        String teacher = new String();

        StringTokenizer teacherArray = new StringTokenizer(request.getParameter("teacherArray").trim(), ";");

        if (request.getParameter("id") != null) {
            id = Long.parseLong(request.getParameter("id"));
        }
        if (request.getParameter("name") != null) {
            name = request.getParameter("name");
        }
        if (request.getParameter("language") != null) {
            language = request.getParameter("language");
        }
        if (request.getParameter("startDate") != null) {
            try {
                String str_date = request.getParameter("startDate");
                System.out.println("StartDatee: " + str_date);
                DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                startDate = (Date) formatter.parse(str_date);
            } catch (ParseException ex) {
                Logger.getLogger(CourseController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (request.getParameter("endDate") != null) {
            try {
                String str_date = request.getParameter("endDate");
                DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                endDate = (Date) formatter.parse(str_date);
            } catch (ParseException ex) {
                Logger.getLogger(CourseController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (request.getParameter("category") != null) {
            category = request.getParameter("category");
        }
        if (request.getParameter("price") != null) {
            price = Double.parseDouble(request.getParameter("price"));
        }
        if (request.getParameter("teacher") != null) {
            teacher = request.getParameter("teacher");
        }
        if (request.getParameter("description") != null) {
            description = request.getParameter("description");
        }

        if (id != 0) {
            //Boolean found = false;
            Course course = dao.get(id);

            //vinden van de huidige categorie van de cursus
            List<Category> categories = cdao.findAll();
            for (Category currentCategory : categories) { //loop door alle categories
                for (Course currentCourse : currentCategory.getCourses()) { //loop door alle courses van een specifieke category
                    if (currentCourse.getName().equals(course.getName())) { //als course overeenkomt met opgegeven course
                        //found = true; //als categorie is gevonden, set bool op true
                        if (!currentCategory.getCategoryID().equals(category)) {//als opgegeven categorie anders is dan huidig                            
                            currentCategory.deleteACourse(course); //verwijder course van de oude category
                            cdao.update(currentCategory);//update oude category

                            Category newCategory = cdao.get(category); //haal category op waar de course in gezet wordt.
                            newCategory.setACourse(course);
                            cdao.update(newCategory);//update nieuwe category
                        }
                    }
                }
            }

            //editten cursus gegevens
            course.setEndDate(endDate);
            course.setStartDate(startDate);
            course.setName(name);
            course.setPrice(price);
            course.getLanguage();
            course.setDescription(description);
            System.out.println("HIER MOET IK OOK KOMEN HOOR");
            //het aanpassen van de docenten.
            Set<User> teachers = new HashSet<User>();
            while (teacherArray.hasMoreTokens()) {
                System.out.println("EN HIER DAN?!");
                User user = udao.get(Long.parseLong(teacherArray.nextToken()));
                user.addCourse(course);
                udao.update(user);
               teachers.add(user);
            }
            dao.update(course);
            course.setUsers(teachers);
            /* if (found == false) {S
             Category newCategory = cdao.get(category); //haal category op waar de course in gezet wordt.
             newCategory.setACourse(course);
             cdao.update(newCategory);//update nieuwe category
             }*/
        } else {
            Course course = new Course(name, language, price, startDate, endDate);
            course.setDescription(description);
            dao.save(course);
            //teacher koppelen aan
            
            Set<User> teachers = new HashSet<User>();
            while (teacherArray.hasMoreTokens()) {
                //System.out.println("Token  :" + teacherArray.nextToken());
                User user = udao.get(Long.parseLong(teacherArray.nextToken()));
                user.addCourse(course);
                udao.update(user);
                teachers.add(user);
            }
            course.setUsers(teachers);
            
            CategoryDao cdao = new CategoryDao(session);
            Category categoryObj = cdao.get(category);
            categoryObj.setACourse(course);
            cdao.update(categoryObj);
        }

        forward(request, response, null);
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String titel)
            throws ServletException, IOException {

        request.setAttribute("pageTitle", titel);

        String address = "/courseManager.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
